/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    int goodNodes(TreeNode *root)
    {
        int result = 0;
        function<void(TreeNode *, int)> dfs = [&](TreeNode *tree, int pathMax)
        {
            if (tree == nullptr)
            {
                return;
            }
            if (tree->val >= pathMax)
            {
                ++result;
            }

            pathMax = max(pathMax, tree->val);
            dfs(tree->left, pathMax);
            dfs(tree->right, pathMax);
        };
        dfs(root, INT_MIN);
        return result;
    }
};